<?php

include_once("config.php");

function getUserID(){
    $url="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".ACCESS_TOKEN."&code=".$_GET["code"];
    $ch = curl_init();
    //设置选项，包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
//    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
//    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //执行并获取HTML文档内容
    $output = curl_exec($ch);

    //释放curl句柄
    curl_close($ch);

    $res = json_decode($output);

    if($res->errcode!="0")
    {
        die($res->errmsg);
    }

    return $res->UserId;
}

function getUserInfo($userID)
{
    $userInfo = array("userID"=>$userID,"studentID"=>-1,"permission"=>0,"class"=>-1);
    try {
        $connPdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'squidward_top', '789456');
        $connPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "SELECT * FROM test.user WHERE userID = '$userID'";
        $records = $connPdo->query($sql)->fetchAll();
    } catch (PDOException $e) {
        die("错误\n{$e->getMessage()}");
    }

    if(count($records)!=1)
    {
        return($userInfo);
    }

    $userInfo["studentID"]=$records[0]["studentID"];
    $userInfo["permission"]=$records[0]["permission"];
    $userInfo["class"]=$records[0]["class"];
    return($userInfo);
}

if(!isset($_GET["code"]))
{
    die("参数错误");
}

//echo("11111");
$userID = getUserID();
$userInfo = getUserInfo($userID);
print_r($userInfo);

?>
